package com.vilynn.interview.test;

import lombok.Setter;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class ThreadPool {
    private Thread[] pool;
    private Queue<Runnable> workList;

    public ThreadPool(int num, int workNum) {
        this.pool = new Thread[num];
        this.workList = new ArrayBlockingQueue<>(workNum);
    }

    public void submit(Runnable work) {
        workList.add(work);
        for (int i = 0; i < pool.length; i++) {
            if (pool[i] == null) {
                pool[i] = new Thread(() -> {
                    while (true) {
                        Runnable runnable = workList.poll();
                        if (runnable == null) {
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            runnable.run();
                        }
                    }
                });
                pool[i].start();
            }
        }
    }

    public static class Work implements Runnable {

        @Setter
        private Runnable work;

        public Work(Runnable work) {
            this.work = work;
        }

        public void run() {
            if (work != null) {
                work.run();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int num = 3;
        ThreadPool pool = new ThreadPool(4, 10);
        for (int i = 0; i < 15; i++) {
            final int a = i;
//            if (i >= num) {
//                Thread.sleep(100);
//            }
            pool.submit(() -> System.out.println(Thread.currentThread().getName() + "--" + a));
        }
        Thread.sleep(1000 * 1);
        System.out.println("----end----");
    }
}
